<template>
  <div class="app-container">
    <div class="operation-container">
      <div class="filter-container">
        <el-form :inline="true">
          <el-form-item label="字典类型名称">
            <el-input v-model="listQuery.name" placeholder="请输入字典类型名称" class="filter-item" />
          </el-form-item>
          <el-form-item label="字典类型标识">
            <el-input v-model="listQuery.type" placeholder="请输入字典类型标识" class="filter-item" />
          </el-form-item>
          <el-form-item label="字典类型状态">
            <el-select v-model="listQuery.status" placeholder="全部" class="filter-item">
              <el-option value="">全部</el-option>
              <el-option
                v-for="item in dict['sys_status']"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button class="filter-item" type="primary" round icon="el-icon-search" @click="handleFilter">
              搜索
            </el-button>
            <el-button class="filter-item" round icon="el-icon-search" @click="handleReset">
              重置
            </el-button>
          </el-form-item>
        </el-form>
        <el-button class="filter-item" type="primary" round icon="el-icon-edit" @click="handleTypeCreate">
          添加字典类型
        </el-button>
      </div>
    </div>

    <div class="operation-container">
      <el-table
        ref="dictTable"
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        height="260"
        row-key="id"
        stripe
        highlight-current-row
      >
        <el-table-column
          label="序号"
          type="index"
          :index="indexMethod"
        />
        <el-table-column label="字典类型名称" prop="name" />
        <el-table-column prop="type" label="字典类型标识">
          <template slot-scope="{row}">
            <span style="color: #1482f0" @click="handleTyptClick(row.type)">{{ row.type }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100">
          <template slot-scope="{row}">
            <template v-for="(item,index) in dict['sys_status']">
              <el-tag v-if="item.value === row.status" :key="index" :type="item.listClass">{{ item.label }}</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="createByName" />
        <el-table-column label="创建时间" prop="createTime">
          <template slot-scope="{row}">
            <i class="el-icon-time margin-right-5" />
            <span>{{ row.createTime | dateFormat }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button type="text" @click="handleTypeUpdate(row)">
              <i class="el-icon-edit" />修改
            </el-button>
            <el-button type="text" @click="handleTypeDelete(row)">
              <i class="el-icon-delete" />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNumber" :limit.sync="listQuery.pageSize" @pagination="getList" />

      <!-- 新增编辑字典类型 -->
      <el-dialog :title="textMap[dialogTypeStatus]" width="500px" append-to-body :visible.sync="dialogType">
        <el-form
          ref="typeForm"
          label-width="100px"
          :model="dictType"
          :rules="typeRules"
        >
          <el-form-item label="类型名称" prop="name">
            <el-input v-model="dictType.name" />
          </el-form-item>
          <el-form-item v-if="dialogTypeStatus !== 'updateType'" label="类型标识" prop="type">
            <el-input v-model="dictType.type" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <template v-for="(item,index) in dict['sys_status']">
              <el-radio :key="index" v-model="dictType.status" :label="item.value">{{ item.label }}</el-radio>
            </template>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="dictType.remark" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogType = false">
            取消
          </el-button>
          <el-button type="primary" @click="submitTypeForm">
            确认
          </el-button>
        </div>
      </el-dialog>
      <el-button class="filter-item" type="primary" round icon="el-icon-edit" @click="handleDataCreate">
        添加字典数据
      </el-button>
      <el-table
        ref="dictDataTable"
        key="2"
        v-loading="listDataLoading"
        :data="listData"
        row-key="id"
        stripe
        highlight-current-row
      >
        <el-table-column
          label="序号"
          type="index"
          :index="indexMethod"
        />
        <el-table-column label="字典数据名称" prop="label" />
        <el-table-column label="字典类型标识" prop="type" />
        <el-table-column label="字典键值" prop="value" />
        <el-table-column label="排序" prop="sort" />
        <el-table-column label="表格回显样式" prop="listClass" />
        <el-table-column label="状态" prop="status" width="100">
          <template slot-scope="{row}">
            <template v-for="(item,index) in dict['sys_status']">
              <el-tag v-if="item.value === row.status" :key="index" :type="item.listClass">{{ item.label }}</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="createByName" />
        <el-table-column label="创建时间" prop="createTime">
          <template slot-scope="{row}">
            <i class="el-icon-time margin-right-5" />
            <span>{{ row.createTime | dateFormat }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button type="text" @click="handleDataUpdate(row)">
              <i class="el-icon-edit" />修改
            </el-button>
            <el-button type="text" @click="handleDataDelete(row)">
              <i class="el-icon-delete" />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 新增编辑字典数据 -->
      <el-dialog :title="textMap[dialogDataStatus]" width="500px" append-to-body :visible.sync="dialogData">
        <el-form
          ref="dataForm"
          label-width="100px"
          :model="dictData"
          :rules="dataRules"
        >
          <el-form-item label="字典类型" prop="type">
            <el-select v-model="dictData.type" placeholder="请选择">
              <template v-for="(item,index) in list">
                <el-option :key="index" :value="item.type" :label="item.name" />
              </template>
            </el-select>
          </el-form-item>
          <el-form-item label="字典标签" prop="label">
            <el-input v-model="dictData.label" />
          </el-form-item>
          <el-form-item label="字典键值" prop="value">
            <el-input v-model="dictData.value" />
          </el-form-item>
          <el-form-item label="排序" prop="sort" style="width: 50%;">
            <el-input-number v-model="dictData.sort" controls-position="right" :min="0" />
          </el-form-item>
          <el-form-item label="表格回显样式" prop="listClass">
            <el-input v-model="dictData.listClass" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <template v-for="(item,index) in dict['sys_status']">
              <el-radio :key="index" v-model="dictData.status" :label="item.value">{{ item.label }}</el-radio>
            </template>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="dictData.remark" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogData = false">
            取消
          </el-button>
          <el-button type="primary" @click="submitDataForm">
            确认
          </el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<script>

import { fetchList, dataList, createType, updateType, deleteType, createData, updateData, deleteData } from '@/api/dict'
import Pagination from '@/components/Pagination'
import { mapGetters } from 'vuex'

export default {
  name: 'DictTable',
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      listLoading: true,
      listDataLoading: false,
      total: 0,
      list: [],
      listData: [],
      listQuery: {
        pageNumber: 1,
        pageSize: 10,
        name: '',
        type: '',
        status: ''
      },
      textMap: {
        updateType: '修改字典类型',
        updateData: '修改字典数据',
        createType: '添加字典类型',
        createData: '添加字典数据'
      },
      dialogType: false,
      dialogTypeStatus: '',
      dialogData: false,
      dialogDataStatus: '',
      menuOptions: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      typeRules: {
        name: [
          { required: true, message: '类型名称不能为空' }
        ],
        type: [
          { required: true, message: '类型标识不能为空' }
        ]
      },
      dataRules: {
        label: [
          { required: true, message: '字典标签不能为空' }
        ],
        value: [
          { required: true, message: '字典键值不能为空' }
        ]
      },
      dictType: {
        id: undefined,
        name: undefined,
        type: undefined,
        status: 'Y',
        remark: undefined
      },
      dictData: {
        id: undefined,
        sort: 0,
        label: undefined,
        value: undefined,
        listClass: undefined,
        status: 'Y',
        remark: undefined
      },
      typt: ''
    }
  },
  computed: {
    ...mapGetters([
      'dict'
    ])
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.2 * 1000)
      })
    },
    // 查询事件
    handleFilter() {
      this.listQuery.pageNumber = 1
      this.getList()
    },
    indexMethod(index) {
      return index + 1
    },
    // 重置查询事件
    handleReset() {
      this.listQuery = {
        pageNumber: 1,
        pageSize: 10,
        name: undefined,
        type: undefined,
        status: undefined
      }
    },
    handleTyptClick(row) {
      this.listDataLoading = true
      this.type = row
      dataList(row).then(response => {
        this.listData = response.data
        setTimeout(() => {
          this.listDataLoading = false
        }, 0.2 * 1000)
      })
    },
    // 创建事件
    handleTypeCreate() {
      this.resetFields('typeForm')
      this.dialogType = true
      this.dialogTypeStatus = 'createType'
    },
    // 修改事件
    handleTypeUpdate(row) {
      this.resetFields('typeForm')
      this.dictType = Object.assign({}, row) // copy obj
      this.dialogType = true
      this.dialogTypeStatus = 'updateType'
    },
    handleTypeDelete(row) {
      deleteType(row.type).then(() => {
        this.getList()
        this.$notify({
          title: '删除完成',
          message: '删除字典类型:（' + row.name + '） 成功！',
          type: 'success',
          duration: 2000
        })
      })
    },
    submitTypeForm() {
      this.$refs['typeForm'].validate(valid => {
        if (valid) {
          if (this.dictType.id) {
            updateType(this.dictType.id, this.dictType).then(() => {
              this.dialogType = false
              this.getList()
              this.$notify({
                title: '修改完成',
                message: '修改字典类型:（' + this.dictType.name + '）成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            createType(this.dictType).then(() => {
              this.dialogType = false
              this.getList()
              this.$notify({
                title: '新增完成',
                message: '新增字典类型:（' + this.dictType.name + '）成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        }
      })
    },
    // 创建事件
    handleDataCreate() {
      this.resetFields('dataForm')
      this.dialogData = true
      this.dialogDataStatus = 'createData'
    },
    // 修改事件
    handleDataUpdate(row) {
      this.resetFields('dataForm')
      this.dictData = Object.assign({}, row) // copy obj
      this.dialogData = true
      this.dialogDataStatus = 'updateData'
    },
    handleDataDelete(row) {
      deleteData(row.id).then(() => {
        this.$notify({
          title: '删除完成',
          message: '删除字典数据:（' + row.label + '） 成功！',
          type: 'success',
          duration: 2000
        })
        this.handleTyptClick(this.type)
      })
    },
    submitDataForm() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.dictData.id) {
            updateData(this.dictData.id, this.dictData).then(() => {
              this.$notify({
                title: '修改完成',
                message: '修改字典数据:（' + this.dictData.label + '）成功',
                type: 'success',
                duration: 2000
              })
              this.dialogData = false
              this.handleTyptClick(this.type)
            })
          } else {
            createData(this.dictData).then(() => {
              this.$notify({
                title: '新增完成',
                message: '新增字典数据:（' + this.dictData.label + '）成功',
                type: 'success',
                duration: 2000
              })
              this.dialogData = false
              this.handleTyptClick(this.type)
            })
          }
        }
      })
    },
    resetFields(form) {
      this.dictType = {
        id: undefined,
        name: undefined,
        type: undefined,
        status: 'Y',
        remark: undefined
      }
      this.dictData = {
        id: undefined,
        sort: 0,
        label: undefined,
        value: undefined,
        listClass: undefined,
        status: 'Y',
        remark: undefined
      }
      if (this.$refs[form] !== undefined) {
        this.$refs[form].resetFields()
      }
    }
  }
}
</script>
